/**
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.solarchallenge.server.servlets.taskservlets;

import static com.google.solarchallenge.server.enums.EmailParameters.APPLICATION_ID;
import static com.google.solarchallenge.server.enums.EmailParameters.DOCUMENT_CATEGORY;
import static com.google.solarchallenge.server.enums.EmailParameters.DOCUMENT_STATUS;
import static com.google.solarchallenge.server.enums.EmailParameters.EMAIL_CATEGORY;
import static com.google.solarchallenge.server.enums.EmailParameters.ENCODED_APPLICANT_KEY;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.utils.SystemProperty;
import com.google.solarchallenge.server.domain.ApplicantDao;
import com.google.solarchallenge.server.domain.UserAccountDao;
import com.google.solarchallenge.server.enums.EmailCategory;
import com.google.solarchallenge.server.persistence.PMF;
import com.google.solarchallenge.shared.ApplicationDocumentCategory;

import java.util.Properties;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet to handle Tasks for sending Emails asynchronously.
 *
 * @author Arjun Satyapal
 */
public class SendEmailServlet extends HttpServlet {
  private Logger logger = Logger.getLogger(SendEmailServlet.class.getName());

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) {
    String emailCategory = request.getParameter(
        EMAIL_CATEGORY.getPublicString());
    String encodedApplicantKey = request.getParameter(
        ENCODED_APPLICANT_KEY.getPublicString());
    String applicationId = request.getParameter(
        APPLICATION_ID.getPublicString());

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    Message message = new MimeMessage(session);
    Key userAccKey = KeyFactory.stringToKey(encodedApplicantKey);
    PersistenceManager pm = PMF.getPersistenceManager();

    try {
      UserAccountDao userDao = pm.getObjectById(
          UserAccountDao.class, userAccKey);
      ApplicantDao applicantDao = userDao.getApplicantDao();

      String senderEmail = "noreply@" + SystemProperty.applicationId.get()
          + ".appspotmail.com";
      message.addRecipient(RecipientType.TO,
          new InternetAddress(userDao.getEmail()));
      message.setFrom(new InternetAddress(senderEmail));

      EmailCategory category = EmailCategory.valueOf(emailCategory);
      switch (category) {
        case FILE_UPLOADED:
          ApplicationDocumentCategory docCategory =
              ApplicationDocumentCategory.valueOf(
                  request.getParameter(DOCUMENT_CATEGORY.getPublicString()));
          String subject = "ApplicationId[" + applicationId
              + "] : Successfully uploaded document : " + docCategory;
          message.setSubject(subject);

          String msgBody = "Current Status for Document[" + docCategory + "] = "
              + request.getParameter(DOCUMENT_STATUS.getPublicString());
          message.setText(msgBody);
          break;

        default :
          logger.severe("Received task for sending email for "
              + "unsupportedCategory : " + category);
      }

      Transport.send(message);
    } catch (AddressException e) {
      // TODO(arjuns): Auto-generated catch block
      e.printStackTrace();
      logger.severe(e.getLocalizedMessage());
    } catch (MessagingException e) {
      // TODO(arjuns): Auto-generated catch block
      e.printStackTrace();
      logger.severe(e.getLocalizedMessage());
    } catch (Throwable e) {
      logger.severe(e.getLocalizedMessage());
    } finally {
      pm.close();
    }
  }
}
